import { customRef, ref, watch } from "vue";
import { BaseFormItem } from "@/components/form/formItem/FormItemMeta";

export default function FormItemCtrl(
  props: BaseFormItem,
  emit: (
    event: "update:modelValue" | "myChange" | "input" | "change",
    ...args: unknown[]
  ) => void
) {
  const debounceRef = (delay = 0, name = "modelValue") => {
    let _value = props[name];
    let isInput = false;
    let timeout: NodeJS.Timeout;

    return customRef((track, trigger) => {
      return {
        get() {
          track();
          if (isInput) {
            return _value;
          } else {
            return props[name];
          }
        },
        set(newValue) {
          isInput = true;
          _value = newValue; // 绑定值
          trigger(); // 组件内部刷新模板
          clearTimeout(timeout); // 清掉上一次的计时
          timeout = setTimeout(() => {
            // 修改 modelValue 属性
            emit("update:modelValue", newValue); // 提交给父组件
            // emit(`update:${name}`, newValue); // 提交给父组件, 动态值, 当前不可用.
            // 用于区分是哪个组件触发的事件。
            emit("myChange", newValue, props.formCtrlId, props.colName);
            isInput = false;
          }, delay);
        },
      };
    });
  };

  const value = debounceRef();
  const mySubmit = (val: string | unknown) => {
    emit("update:modelValue", val); // 修改 modelValue 属性
    emit("myChange", val, props.formCtrlId, props.colName);
    emit("input", val);
    emit("change", val);
  };

  const myDate = ref();

  const dateMange = () => {
    if (typeof value.value === "string") {
      myDate.value = new Date(value.value);
    }

    if (props.controlType === "week") {
      // 把周数转换成日期
      const str = value.value as string;
      const arr = str.split("w") as Array<string>;
      if (arr.length > 1) {
        myDate.value = new Date(
          new Date(arr[0] + "-1-1").valueOf() +
            Number(arr[1]) * 7 * 24 * 3600000
        );
      }
    }
    // 监听属性，设置给 myDate
    watch(
      () => value.value as string,
      (newValue: string) => {
        if (props.controlType === "week") {
          // 把周数转换成日期
          const arr = newValue.split("w");
          if (arr.length > 1) {
            myDate.value = new Date(
              new Date(arr[0] + "-1-1").valueOf() +
                (Number(arr[1]) - 1) * 7 * 24 * 3600000
            );
          }
        } else {
          myDate.value = newValue === null ? null : new Date(newValue);
        }
      }
    );
  };

  const myChange = (_val: Date) => {
    const val = _val;
    let re = "";
    if (val !== null) {
      const year = val.getFullYear();
      const month = (val.getMonth() + 1).toString().padStart(2, "0");
      const day = val.getDate().toString().padStart(2, "0");

      const hour = val.getHours().toString().padStart(2, "0");
      const mm = val.getMinutes().toString().padStart(2, "0");
      const ss = val.getSeconds().toString().padStart(2, "0");

      switch (props.controlType) {
        case "date": // 日期
          re = `${year}-${month}-${day}`;
          break;
        case "datetime": // 日期 + 时间
          re = `${year}-${month}-${day} ${hour}:${mm}:${ss}`;
          break;
        case "month": // 年 + 月
          re = `${year}-${month}`;
          break;
        case "week": // 第几周。直接去dom找。没发现更好的方法
          setTimeout(() => {
            const inputElement = document.getElementsByName(
              "w" + props.formCtrlId
            )[0] as HTMLInputElement;
            re = inputElement.value;
            re = re.replace(" 第", "w").replace("周", "");
            mySubmit(re); // 提交给父组件
          }, 500);
          break;
        case "year": // 年
          re = year.toString();
          break;
        default:
          re = `${year}-${month}-${day} ${hour}:${mm}:${ss}`;
          break;
      }
    }
    mySubmit(re); // 提交给父组件
  };

  return { value, mySubmit, myDate, dateMange, myChange };
}
